package com.yicong.ants.view.dialog;

import android.graphics.Bitmap;
import android.os.Environment;
import android.view.View;

import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.util.FileUtils;
import com.github.chrisbanes.photoview.PhotoView;
import com.yicong.ants.R;
import com.yicong.ants.utils.BitmapUtils;
import com.yicong.ants.utils.ToastUtils;

import java.io.File;

/**
 * 长按弹出是否保存图片
 *
 * @author LinDingQiang
 * @description
 * @time 4/20/21 10:06 PM
 * @email dingqiang.l
 */
public class SaveImageDialog extends BaseNiceDialog {
    private CallBack mListener;
    private PhotoView mPhotoView;


    public static SaveImageDialog newInstance() {
        SaveImageDialog dialog = new SaveImageDialog();
        dialog
                .setHeight((int) (UiHelper.getScreenHeight() * 0.2))
                .setOutCancel(true)
                .setDimAmount(0.3f)
                .setShowBottom(true);
        return dialog;
    }

    public SaveImageDialog setPhotoView(PhotoView photoView) {
        this.mPhotoView = photoView;
        return this;
    }

    public SaveImageDialog setConvertListener(CallBack listener) {
        this.mListener = listener;
        return this;
    }

    @Override
    public int intLayoutId() {
        return R.layout.dialog_save_image;
    }

    @Override
    public void convertView(NiceViewHolder holder, BaseNiceDialog dialog) {

        holder.setOnClickListener(R.id.tv_save_img, v -> {
            mPhotoView.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(mPhotoView.getDrawingCache());
            mPhotoView.setDrawingCacheEnabled(false);
            File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath());
            FileUtils.createOrExistsDir(dir);
            File imageFile = new File(dir, "jpg_" + System.currentTimeMillis() + ".jpg");
            BitmapUtils.compressBmpToFile(bitmap, imageFile);
            UiHelper.showToast("图片已保存 " + imageFile.getAbsolutePath());
            dialog.dismiss();
        }).setOnClickListener(R.id.tv_cancel, v -> dialog.dismiss());
    }


    public interface CallBack {
        void onItemClick();
    }
}
